package com.itheima.health.controller;

import com.itheima.health.entity.Result;
import com.itheima.health.exception.MyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @program: health_parent
 * @description: 异常处理
 * @author: HuChunping
 * @create: 2021-01-08 15:59
 **/
// 因为这里返回的是字符串，不是跳转，所以用@RestControllerAdvice
@RestControllerAdvice
public class MyExceptionAdvice {
    // 使用log日志，MyExceptionAdvice.class能够显示是哪个类哪里的异常
    private static final Logger log = LoggerFactory.getLogger(MyExceptionAdvice.class);

    /**
    * @Description: 业务异常的处理
    * @Param: [e]
    * @return: com.itheima.health.entity.Result
    * @Author: HuChunping
    * @Date: 2021/1/8-16:05
    */
    // service抛出的异常会被controller远程调用接受，controller再抛，被Advice拦截，@RestControllerAdvice将异常包装json字符串返回给前端
    // 抛出MyException异常会在此处被拦截(需要抛出异常的接口也抛出此自定义异常)；否者抛出的MyException会被dubbo包装为RuntimeException
    @ExceptionHandler(MyException.class)
    public Result handleMyException(MyException e) {
        // 业务异常，直接返回异常信息
        return new Result(false, e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(MyException e) {
        // 日志记录未知异常
        log.error("发生未知异常");
        // 返回未知异常信息
        return new Result(false, "未知异常，请联系管理员");
    }
}
